#!/bin/bash
set -e

echo "Update the docker_entrypoint.sh script of the warehouse to the system /usr/local/bin/docker_entrypoint.sh"
cat /scripts/docker_entrypoint.sh >/usr/local/bin/docker_entrypoint.sh
chmod +x /scripts/dosign.js
chmod +x /scripts/dolottery.js
chmod +x /scripts/dotask.js
chmod +x /scripts/dointegral.js

function rand(){
    min=$1
    max=$(($2 - $min +1 ))
    num=$(date +%s%N)
    echo $(($num%$max + $min))
}

#chmod +x /scripts/test.sh
if [ $CUSTOM_CRONTAB_HOUR ]; then
    echo "Start crontab task main process..."
    echo "start up the crondtab..."
    currentTime=$(date +%F%n%T)
    echo "Current system time is $currentTime"
    
    random_m=$(rand 1 30)
    random_m1=`expr $random_m + $(($(rand 5 11)))`
    random_m2=`expr $random_m1 + $(($(rand 5 11)))`
    random_m3=`expr $random_m2 + $(($(rand 5 11)))`
    
    clearLog="50 23 */7 * *  rm -rf /scripts/logs"
    dosignCommand="${random_m} ${CUSTOM_CRONTAB_HOUR} * * *  node /scripts/dosign.js >> /scripts/logs/sign.log 2>&1"
    dolotteryCommand="${random_m1} ${CUSTOM_CRONTAB_HOUR} * * *  node /scripts/dolottery.js >> /scripts/logs/lottery.log 2>&1"
    dotaskCommand="${random_m2} ${CUSTOM_CRONTAB_HOUR} * * *  node /scripts/dotask.js >> /scripts/logs/task.log 2>&1"
    dodointegralCommand="${random_m3} ${CUSTOM_CRONTAB_HOUR} * * *  node /scripts/dointegral.js >> /scripts/logs/dointegral.log 2>&1"
    echo "${dosignCommand}"
    echo "${dolotteryCommand}"
    echo "${dotaskCommand}"
    echo "${dodointegralCommand}"

    sed -i '/scripts/d' /etc/crontabs/root

    echo "${dosignCommand}" >> /etc/crontabs/root
    echo "${dolotteryCommand}" >> /etc/crontabs/root
    echo "${dotaskCommand}" >> /etc/crontabs/root
    echo "${dodointegralCommand}" >> /etc/crontabs/root
    echo "${clearLog}" >> /etc/crontabs/root
    crontab -l 
    crond -f
else
        echo "The crontab time CUSTOM_CRONTAB_HOUR is not set in docker-compose.yml"
fi
